package ssm.config;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Collection;
import java.util.Date;

public class TransactionPreciseShardingAlgorithm implements PreciseShardingAlgorithm<Date> {

    private static final DateTimeFormatter YYYY_MM = DateTimeFormatter.ofPattern("YYYYMM");
    private static final String SEPARATOR = "_";

    private static LocalDateTime dateToLocalDateTime(Date date) {
        Instant instant = date.toInstant();
        ZoneId zoneId = ZoneId.systemDefault();
        // atZone()方法返回在指定时区从此Instant生成的ZonedDateTime。
        return instant.atZone(zoneId).toLocalDateTime();

    }

    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<Date> shardingValue) {
        String logicTableName = shardingValue.getLogicTableName();
        Date date = shardingValue.getValue();
        return logicTableName + SEPARATOR + YYYY_MM.format(dateToLocalDateTime(date));
    }
}
